import React, { useState } from 'react';
import { Input } from 'antd';
import { connect, formatMessage, history } from 'umi';
import { DrawerForm, Form } from '@/zero';
import { validatePassword } from '@/utils/default';
import LoginForm from '../_components/LoginForm';
import styles from './index.less';

const mapStateToProps = ({ loading }) => ({
  loadingGlobal: loading.global,
});

const mapDispatchToProps = (dispatch) => ({
  userLogin: (payload) =>
    dispatch({
      type: `global/userLogin`,
      payload,
    }),
  resetPassword: (payload) =>
    dispatch({
      type: `global/resetPassword`,
      payload,
    }),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)((props) => {
  const { userLogin, resetPassword, loadingGlobal } = props;

  const [errorMessage, setErrorMessage] = useState('');

  const [currentUser, setCurrentUser] = useState({});

  const onSubmit = (newRecord) => {
    userLogin(newRecord).then((response) => {
      if (response.success) {
        const { firstLogin, isPasswordExpire } = response.data;
        const newPasswordExpired = !!firstLogin || !!isPasswordExpire;
        if (newPasswordExpired) {
          setCurrentUser({
            ...response.data,
            newPasswordExpired,
          });
        } else {
          history.push('/');
        }
      } else {
        setErrorMessage(response.data.message);
      }
    });
  };

  return (
    <div className={styles.main}>
      <div className={styles.left}>
        <div style={{ marginTop: '30vh' }}>
          <p
            style={{
              fontFamily: 'PingFangSC-Regular',
              fontSize: '40px',
              color: ' #FFFFFF',
              textAlign: 'center',
              marginBottom: '0',
            }}
          >
            Welcome to
          </p>
          <p
            style={{
              fontFamily: 'Arial-BoldMT',
              fontSize: '52px',
              color: '#FFFFFF',
              textAlign: 'center',
              marginTop: '16px',
              marginBottom: '0',
            }}
          >
            {formatMessage({ id: 'project.long-name' })}
          </p>
          <p
            style={{
              fontFamily: 'PingFangSC-Regular',
              fontSize: '24px',
              color: '#FFFFFF',
              textAlign: 'center',
              marginTop: '24px',
            }}
          >
            Login to access your account
          </p>
        </div>
      </div>

      <div className={styles.right}>
        <img
          alt="logo"
          src="/images/logo.png"
          style={{
            marginTop: '6vh',
            marginLeft: '44vw',
          }}
        />
        <div style={{ marginTop: '10vh' }}>
          <p
            style={{
              fontFamily: 'PingFangSC-Regular',
              fontSize: '40px',
              fontWeight: 'bold',
              color: '#000000',
              textAlign: 'center',
            }}
          >
            {formatMessage({ id: 'project.long-name' })}
          </p>
          <p
            style={{
              fontFamily: 'PingFangSC-Regular',
              fontSize: '24px',
              color: '#888B8D',
              textAlign: 'center',
              lineHeight: '30px',
              marginBottom: '0',
            }}
          >
            &nbsp;
          </p>

          <div style={{ width: '22vw', margin: '0 auto' }}>
            <LoginForm
              account={{
                errorMessage,
                loading: loadingGlobal,
              }}
              mobile={{
                errorMessage,
                loading: loadingGlobal,
              }}
              onSubmit={onSubmit}
            />
          </div>
        </div>

        {currentUser.newPasswordExpired && (
          <DrawerForm
            width={600}
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ marginRight: '10px' }}>{formatMessage({ id: '密码已失效' })}</span>
              </div>
            }
            items={[
              {
                child: (
                  <Form.Item shouldUpdate noStyle>
                    {(form) => (
                      <>
                        <Form.Item
                          label={formatMessage({ id: '密码' })}
                          name="oldpwd"
                          rules={[
                            {
                              required: true,
                              message: formatMessage({
                                id: '请输入密码',
                              }),
                            },
                          ]}
                        >
                          <Input.Password />
                        </Form.Item>

                        <Form.Item
                          label={<span>{formatMessage({ id: '新密码' })}</span>}
                          name="newpwd"
                          rules={[
                            {
                              required: true,
                              message: formatMessage({
                                id: '请输入新密码',
                              }),
                            },
                            {
                              validator: (rule, value, callback) => {
                                const { result, message } = validatePassword(value, {
                                  minLength: currentUser?.company?.passwordNumber,
                                  typeKeys: currentUser?.company?.passwordStrength?.split(','),
                                });
                                if (result) {
                                  callback();
                                } else {
                                  callback(message);
                                }
                              },
                            },
                          ]}
                        >
                          <Input.Password />
                        </Form.Item>

                        <Form.Item
                          label={<span>{formatMessage({ id: '确认密码' })}</span>}
                          name="rePassword"
                          dependencies={['newpwd']}
                          rules={[
                            {
                              required: true,
                              message: formatMessage({
                                id: '请输入确认密码',
                              }),
                            },
                            {
                              validator: (rule, value, callback) => {
                                if (value !== form.getFieldValue('newpwd')) {
                                  callback(formatMessage({ id: '两次输入的密码不匹配' }));
                                } else {
                                  callback();
                                }
                              },
                            },
                          ]}
                        >
                          <Input.Password />
                        </Form.Item>
                      </>
                    )}
                  </Form.Item>
                ),
              },
            ]}
            visible={currentUser.newPasswordExpired}
            closable={false}
            cancelButtonProps={{ style: { display: 'none' } }}
            onOk={(newRecord, success, error) => {
              resetPassword({
                ...currentUser,
                ...newRecord,
              }).then((response) => {
                if (response.success) {
                  success();
                  window.location.reload();
                } else {
                  error(response.data?.message);
                }
              });
            }}
          />
        )}
      </div>
    </div>
  );
});
